package com.sk.weichat.adapter;

import android.content.Context;
import android.graphics.drawable.Animatable;
import android.support.annotation.NonNull;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.LayoutHelper;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.SingleLayoutHelper;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.facebook.drawee.controller.BaseControllerListener;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.flexbox.JustifyContent;
import com.sk.weichat.R;
import com.sk.weichat.bean.DynamicBean;
import com.sk.weichat.bean.circle.PublicMessage;
import com.sk.weichat.helper.AvatarHelper;
import com.sk.weichat.ui.circle.DynamicDetailsActivity;
import com.sk.weichat.util.FrescoUtils;
import com.sk.weichat.util.TimeUtils;
import com.sk.weichat.util.ViewPiexlUtil;

import java.util.ArrayList;
import java.util.List;


import static com.sk.weichat.adapter.DynamicMultiItemAdapter.IMAGE_X_MAX_SIZE;
import static com.sk.weichat.adapter.DynamicMultiItemAdapter.IMAGE_X_MIN_SIZE;
import static com.sk.weichat.adapter.DynamicMultiItemAdapter.IMAGE_Y_MAX_SIZE;
import static com.sk.weichat.adapter.DynamicMultiItemAdapter.IMAGE_Y_MIN_SIZE;

/**
 * @author lzs
 * @date 2019/10/28
 * Email:343067508@qq.com
 **/
public class DynamicHeadAdapter extends DelegateAdapter.Adapter {
    DynamicBean dynamicBean;
    Context context;
    RecyclerView.RecycledViewPool recycledViewPool;

    public DynamicHeadAdapter(DynamicBean dynamicBean, Context context) {
        this.dynamicBean = dynamicBean;
        this.context = context;
        recycledViewPool = new RecyclerView.RecycledViewPool();
    }

    GestureDetector detector;

    @Override
    public LayoutHelper onCreateLayoutHelper() {
        return new SingleLayoutHelper();
    }

    @NonNull
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        View view = null;
        if (dynamicBean.getItemType() == DynamicBean.type_voice) {
            //语音
            view = LayoutInflater.from(context).inflate(R.layout.item_dynamic_voice, null);
        } else if (dynamicBean.getItemType() == DynamicBean.type_single_image) {
            //单张图
            view = LayoutInflater.from(context).inflate(R.layout.item_dynamic_image_one, null);
        } else if (dynamicBean.getItemType() == DynamicBean.type_grid_image) {
            //多张图
            view = LayoutInflater.from(context).inflate(R.layout.item_dynamic_image_grid, null);
        } else if (dynamicBean.getItemType() == DynamicBean.type_short_video) {
            //视频
            view = LayoutInflater.from(context).inflate(R.layout.item_dynamic_details_video_header, null);
        }
        VirtualLayoutManager.LayoutParams lp = new VirtualLayoutManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(lp);

        return new HeadHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int i) {
        HeadHolder headHolder = (HeadHolder) viewHolder;
        PublicMessage.Body body = dynamicBean.getBody();
        FrescoUtils.loadImage(headHolder.ivAvatar, AvatarHelper.getAvatarUrl(dynamicBean.getUserId(), true));
        addOnClickListener(headHolder.ivAvatar, i);
        //用户昵称
        headHolder.tvName.setText(dynamicBean.getNickName());
        addOnClickListener(headHolder.tvName, i);
        //时间
        headHolder.tvTime.setText(TimeUtils.getFriendlyTimeDesc(context, dynamicBean.getTime()));
        //内容
        headHolder.tvContent.setText(body.getText());
        addOnClickListener(headHolder.tvContent, i);
        //地点
        headHolder.tvLocation.setText(dynamicBean.getLocation());
        addOnClickListener(headHolder.tvLocation, i);
        //关注或未关注
        setAttentionStatus(headHolder.tvAttention, dynamicBean.getIfAttention());
        addOnClickListener(headHolder.tvAttention, i);
        //
        //话题列表
        if (dynamicBean.getTopicNames() != null && dynamicBean.getTopicNames().size() > 0) {
            RecyclerView recyclerViewTopics = headHolder.recyclerView_topic;
            //流式布局
            FlexboxLayoutManager layoutManager1 = new FlexboxLayoutManager(context);
            layoutManager1 = new FlexboxLayoutManager(context);
            layoutManager1.setFlexDirection(FlexDirection.ROW);
            layoutManager1.setJustifyContent(JustifyContent.FLEX_START);
            layoutManager1.setFlexWrap(FlexWrap.WRAP);
            recyclerViewTopics.setLayoutManager(layoutManager1);

            recyclerViewTopics.setAdapter(getTopicsAdapter(dynamicBean.getTopicNames()));
        }
        if (dynamicBean.getItemType() == DynamicBean.type_voice) {
            //语音


        } else if (dynamicBean.getItemType() == DynamicBean.type_single_image) {
            //单张图
            //图片
            if (body.getImages() != null && body.getImages().size() > 0 && !TextUtils.isEmpty(body.getImages().get(0).getOriginalUrl())) {
                FrescoUtils.loadImageControllerListener(headHolder.ivSingleImage, body.getImages().get(0).getOriginalUrl(), new BaseControllerListener<ImageInfo>() {
                    @Override
                    public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable anim) {
                        if (imageInfo == null) {
                            return;
                        }
                        //重新设置图片的高度宽度
                        int h = imageInfo.getHeight();
                        int w = imageInfo.getWidth();
                        float[] outSize = getScaleSize(context, w, h);
                        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) headHolder.ivSingleImage.getLayoutParams();
                        lp.height = (int) outSize[1];
                        lp.width = (int) outSize[0];
                        headHolder.ivSingleImage.setLayoutParams(lp);
                    }

                    @Override
                    public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

                    }

                    @Override
                    public void onFailure(String id, Throwable throwable) {
                        throwable.printStackTrace();
                    }
                });

            }
        } else if (dynamicBean.getItemType() == DynamicBean.type_grid_image) {
            //多张图
            RecyclerView recyclerView = headHolder.recyclerView;
//        GridDivider divider = new GridDivider(recyclerView.getContext(), ViewPiexlUtil.dp2px(recyclerView.getContext(), 8), 0, false, false,recyclerView.getResources().getColor(R.color.white) );
//        recyclerView.addItemDecoration(divider);
            //四个数据的时候排列顺序有变化每行只排两个,第3个使用空数据占位
            List<PublicMessage.Resource> resouces = dynamicBean.getBody().getImages();
            List<PublicMessage.Resource> imgs = new ArrayList<>();
            if (resouces.size() == 4) {
                imgs.add(resouces.get(0));
                imgs.add(resouces.get(1));
                //空数据
                PublicMessage.Resource resource = new PublicMessage.Resource();
                resource.setOriginalUrl("");
                imgs.add(resource);
                imgs.add(resouces.get(2));
                imgs.add(resouces.get(3));
            }
            if (resouces.size() == 2) {
                recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 2));
            } else {
                recyclerView.setLayoutManager(new GridLayoutManager(recyclerView.getContext(), 3));
            }
            BaseQuickAdapter<PublicMessage.Resource, BaseViewHolder> adapter = new BaseQuickAdapter<PublicMessage.Resource, BaseViewHolder>(R.layout.item_dynamic_image, resouces.size() == 4 ? imgs : resouces) {
                @Override
                protected void convert(BaseViewHolder holder1, PublicMessage.Resource item) {
                    //Log.e("lzs", "convert:" + item.getOriginalUrl());
                    if (!TextUtils.isEmpty(item.getOriginalUrl())) {
                        FrescoUtils.loadImage(holder1.getView(R.id.iv_image), item.getOriginalUrl());
                    } else {
                        FrescoUtils.setImageRes(holder1.getView(R.id.iv_image), R.drawable.shape_corner_8dp_solid_white);
                    }
                }
            };
            recyclerView.setRecycledViewPool(recycledViewPool);
            recyclerView.setAdapter(adapter);
        } else if (dynamicBean.getItemType() == DynamicBean.type_short_video) {
            if (dynamicBean.getBody().getVideos() == null || dynamicBean.getBody().getVideos().size() == 0) {
                return;
            }
            headHolder.viewTouch.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    if (headHolder.viewTouch.getMeasuredHeight() < 10) {
                        //动态设置cover封面的大小
                        int[] outSize = null;
                        if (dynamicBean.getRotation() / 90 > 0) {
                            Log.e("lzs", dynamicBean.getVideoHeight() + "  " + dynamicBean.getVideoWidth());
                            //旋转
                            outSize = getVideoSize(headHolder.viewTouch.getMeasuredWidth(), dynamicBean.getVideoHeight(), dynamicBean.getVideoWidth());
                        } else {
                            outSize = getVideoSize(headHolder.viewTouch.getMeasuredWidth(), dynamicBean.getVideoWidth(), dynamicBean.getVideoHeight());
                        }
                        ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) headHolder.viewTouch.getLayoutParams();
                        lp.width = outSize[0];
                        lp.height = outSize[1];
                        Log.e("lzs", "outSize width:" + outSize[0] + "  outSize height:" + outSize[1]);
                        headHolder.viewTouch.setLayoutParams(lp);
                        if (dynamicBean.getBody().getImages() == null || dynamicBean.getBody().getImages().size() == 0) {
                            return;
                        }
                    }
                }
            });
            if (dynamicBean.isActive()) {
                Log.e("lzs", "isActive");
                headHolder.ivCover.setVisibility(View.GONE);
            } else {
                Log.e("lzs", "is not Active");
                headHolder.ivCover.setVisibility(View.VISIBLE);
                if (dynamicBean.getBody().getImages() != null && dynamicBean.getBody().getImages().size() > 0) {
                    PublicMessage.Resource image = dynamicBean.getBody().getImages().get(0);
                    FrescoUtils.loadImage(headHolder.ivCover, image.getOriginalUrl());
                }
            }
            //addOnClickListener(headHolder.viewTouch, i);
        }
    }

    public static int[] getVideoSize(int maxWidth, int originalVideoWidth, int originalVideoHeight) {
        int[] outSize = new int[2];
        float scale = originalVideoWidth * 1.0f / maxWidth;
        outSize[1] = (int) (originalVideoHeight / scale);
        outSize[0] = maxWidth;
        return outSize;
    }

    private void addOnClickListener(View view, int position) {
        view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("lzs", "onClick:" + listener);
                if (listener != null) {
                    listener.onItemClick(view, position);
                }
            }
        });
    }

    private void setAttentionStatus(TextView tvAttention, int isAttention) {
        tvAttention.setVisibility(View.VISIBLE);
        if (isAttention == 1) {
            tvAttention.setText("已关注");
            tvAttention.setTextAppearance(tvAttention.getContext(), R.style.text_attention_select);
        } else {
            tvAttention.setText("+ 关注");
            tvAttention.setTextAppearance(tvAttention.getContext(), R.style.text_attention_nomal);
        }
    }

    private float[] getScaleSize(Context context, float originalW, float originalH) {
        float[] outSize = new float[2];
        int minX = ViewPiexlUtil.dp2px(context, IMAGE_X_MIN_SIZE);
        int minY = ViewPiexlUtil.dp2px(context, IMAGE_Y_MIN_SIZE);
        int maxX = ViewPiexlUtil.dp2px(context, IMAGE_X_MAX_SIZE);
        int maxY = ViewPiexlUtil.dp2px(context, IMAGE_Y_MAX_SIZE);
        Log.e("lzs", "minX:" + minX + " minY:" + minY + "   originalW:" + originalW + "  originalH:" + originalH);
        if (originalW > originalH) {
            //横向图
            if (originalW < minX) {
                outSize[0] = minX;
                outSize[1] = originalH * 1.0f / originalW * minX;
            } else {
                float scale = originalH * 1.0f / originalW;
                if (scale < 0.3) {
                    //图片特别宽，高度设置为最大高度的一半
                    outSize[1] = maxY / 2;
                } else {
                    //限制高度不能超过最大高度
                    outSize[1] = Math.min((int) (scale * maxY), maxY);
                }
                outSize[0] = maxX;
            }
        } else if (originalW == originalH) {
            outSize[0] = maxX;
            outSize[1] = maxX;
        } else {
            //竖向图
            if (originalH < minY) {
//                if (originalW > min) {
                //如果原始宽度大于最大宽度，需要缩放
                outSize[0] = minY;
                float scale = originalW * 1.0f / minY;
                Log.e("lzs", "originalH / scale:" + originalH / scale);
                outSize[1] = Math.min(originalH / scale, maxY);
//                } else {
//                    outSize[0] = originalW;
//                    outSize[1] = originalH;
//                }
            } else {
                float scale = originalW * 1.0f / originalH;
                if (scale < 0.3) {
                    //长宽比例较大,图片特别长，宽度设置为最大宽度的一半
                    outSize[0] = maxY / 2;
                } else {
                    //取原图按比例缩放后的值和最大宽度中较小者
                    outSize[0] = Math.min((int) (scale * maxY), maxY);
                }
                outSize[1] = maxY;
            }
        }
        return outSize;
    }

    @Override
    public int getItemCount() {
        return 1;
    }

    class HeadHolder extends RecyclerView.ViewHolder {
        public SimpleDraweeView ivAvatar;
        public TextView tvName;
        public TextView tvTime;
        public TextView tvContent;
        public TextView tvLocation;
        public SimpleDraweeView ivSingleImage; // 单张图片

        public SimpleDraweeView ivCover; //视频封面

        public View viewTouch;
        public TextView tvAttention;//关注
        public ImageView ivMore; // 更多

        public RecyclerView recyclerView;//图片列表

        public RecyclerView recyclerView_topic; // 话题列表

        public ImageView ivGreat; //点赞
        public ImageView ivComment; //评论
        public ImageView ivCollection; //收藏
        public ImageView ivSend; //转发


        public HeadHolder(@NonNull View itemView) {
            super(itemView);
            recyclerView = itemView.findViewById(R.id.recyclerview);
            recyclerView_topic = itemView.findViewById(R.id.recyclerview_topics);
            ivAvatar = itemView.findViewById(R.id.iv_avatar);
            ivSingleImage = itemView.findViewById(R.id.iv_image);
            tvName = itemView.findViewById(R.id.tv_name);
            tvContent = itemView.findViewById(R.id.tv_content);
            tvTime = itemView.findViewById(R.id.tv_time);
            tvLocation = itemView.findViewById(R.id.tv_location);
            ivMore = itemView.findViewById(R.id.iv_more_action);
            tvAttention = itemView.findViewById(R.id.tv_attention);
            ivCover = itemView.findViewById(R.id.iv_cover);
            viewTouch = itemView.findViewById(R.id.view_touch);
        }
    }


    /**
     * 话题适配器
     *
     * @return
     */
    private BaseQuickAdapter<String, BaseViewHolder> getTopicsAdapter(List<String> topics) {
        BaseQuickAdapter<String, BaseViewHolder> adapter = new BaseQuickAdapter<String, BaseViewHolder>(R.layout.item_dynamic_topic, topics) {
            @Override
            protected void convert(BaseViewHolder helper, String item) {
                helper.setText(R.id.tv_name, "#" + item + "#");
            }
        };
        return adapter;
    }

    public void setListener(OnItemClickListener listener) {
        this.listener = listener;
    }

    private OnItemClickListener listener;

    public interface OnItemClickListener {
        void onItemClick(View view, int position);
    }

}
